package com.sky.service.impl;

import com.sky.dto.DataOverViewQueryDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param dataOverViewQueryDTO
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(DataOverViewQueryDTO dataOverViewQueryDTO) {

        StringBuffer dateList = new StringBuffer();
        StringBuffer turnoverList = new StringBuffer();
        LocalDate end = dataOverViewQueryDTO.getEnd();
        for(LocalDate now = dataOverViewQueryDTO.getBegin(); !now.isAfter(end); now = now.plusDays(1))
        {
            LocalDateTime beginTime = LocalDateTime.of(now, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double sum = orderMapper.sumAmountByTime(map);
            if(sum == null)sum = 0.0;
            dateList.append(now);

            turnoverList.append(sum);
            if(!now.equals(end))
            {
                dateList.append(",");
                turnoverList.append(",");
            }
        }
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateList.toString());
        turnoverReportVO.setTurnoverList(turnoverList.toString());
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param dataOverViewQueryDTO
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(DataOverViewQueryDTO dataOverViewQueryDTO) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        LocalDate end = dataOverViewQueryDTO.getEnd();
        for (LocalDate now = dataOverViewQueryDTO.getBegin(); !now.isAfter(end); now = now.plusDays(1))
        {
            LocalDateTime beginTime = LocalDateTime.of(now, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX);
            Integer new_user = userMapper.getUserCountByTime(beginTime, endTime);
            Integer all_user = userMapper.getUserCountByTime(null, endTime);
            dateList.add(now);
            totalUserList.add(new_user);
            newUserList.add(all_user);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param dataOverViewQueryDTO
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(DataOverViewQueryDTO dataOverViewQueryDTO) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        LocalDate end = dataOverViewQueryDTO.getEnd();
        int allOrders = 0;
        int validOrders = 0;

        for (LocalDate now = dataOverViewQueryDTO.getBegin(); !now.isAfter(end); now = now.plusDays(1))
        {
            LocalDateTime beginTime = LocalDateTime.of(now, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer all_order = orderMapper.countByMap(map);
            map.put("status", Orders.COMPLETED);
            Integer valid_order = orderMapper.countByMap(map);
            allOrders += all_order;
            validOrders += valid_order;
            dateList.add(now);
            orderCountList.add(all_order);
            validOrderCountList.add(valid_order);
        }
        double orderCompletionRate = 0.0;
        if(allOrders != 0)orderCompletionRate = 1.0*validOrders/allOrders;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(allOrders)
                .validOrderCount(validOrders)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量统计
     * @param dataOverViewQueryDTO
     * @return
     */
    @Override
    public SalesTop10ReportVO getOrderTop10(DataOverViewQueryDTO dataOverViewQueryDTO) {
        List<String> nameList = new ArrayList<>();
        List<Integer>numberList = new ArrayList<>();
        Map map = new HashMap();
        map.put("beginTime", LocalDateTime.of(dataOverViewQueryDTO.getBegin(), LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(dataOverViewQueryDTO.getEnd(), LocalTime.MAX));
        map.put("status", Orders.COMPLETED);
        List<OrderDetail> orderDetailList = orderDetailMapper.getDishAndNumber(map);
        for (OrderDetail orderDetail : orderDetailList) {
            nameList.add(orderDetail.getName());
            numberList.add(orderDetail.getNumber());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessReport(HttpServletResponse response) {

        //查询数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().plusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getTodayBusinessData(beginTime, endTime);
        //写入文件

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //获得表格sheet标签页
            XSSFSheet sheet = workbook.getSheet("sheet1");
            //写入数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginTime + "~" + endTime);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //受限于模板的行数，下面的每一行每一个cell都必须create
            row = sheet.createRow(7);
            int cnt = 7;
            for (LocalDate now = beginTime; !now.isAfter(endTime); now = now.plusDays(1))
            {
                businessDataVO = workspaceService.getTodayBusinessData(now, now);
                row.createCell(1).setCellValue(now.toString());
                row.createCell(2).setCellValue(businessDataVO.getTurnover());
                row.createCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.createCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.createCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.createCell(6).setCellValue(businessDataVO.getNewUsers());
                row = sheet.createRow(++cnt);
            }

            //用输出流将文件下载到客户端
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);

            //关闭资源
            inputStream.close();
            outputStream.close();
            workbook.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
